//
//  AmuseMenuView.swift
//  DouYuZB
//
//  Created by 刘耀 on 2017/4/14.
//  Copyright © 2017年 深圳多诺信息科技有限公司. All rights reserved.
//

import UIKit

private let kMenuCellID = "kMenuCellID"

class AmuseMenuView: UIView {

    var groups: [AnchorGroup]? {
        didSet {
            
            collectionView.reloadData()
        }
    }
    
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var collectionView: UICollectionView!
    override func awakeFromNib() {
        super.awakeFromNib()
        
        collectionView.register(UINib(nibName: "AmuseMenuViewCell", bundle: nil), forCellWithReuseIdentifier: kMenuCellID)
        // 设置该控件不随这父控件的拉伸而拉伸 .注意这里不添加的话，是不会显示的。因为随着父控件缩放这个视图缩小看不见了
        autoresizingMask = .init(rawValue: 0)
        
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = collectionView.size  // 这个尺寸如果放在 awakeFromNib() 不对，这里拿到的是xib的大小。放在这里拿到的是外界给定的尺寸大小
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        
    }
    
}

// MARK:- 从Xib中快速创建的类方法
extension AmuseMenuView {
    class func amuseMenuView() -> AmuseMenuView {
        return Bundle.main.loadNibNamed("AmuseMenuView", owner: nil, options: nil)?.first as! AmuseMenuView
    }
}

// MARK: - UICollectionViewDataSource
extension AmuseMenuView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if groups == nil { return 0 }
        let pageNum = (groups!.count - 1) / 8 + 1
        pageControl.numberOfPages = pageNum
        return pageNum
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kMenuCellID, for: indexPath) as! AmuseMenuViewCell
        cellData(cell: cell, indexPath: indexPath)
        return cell
    }
    
    private func cellData(cell: AmuseMenuViewCell, indexPath: IndexPath) {
        // 0页 0 ~ 7   1页 8 ~ 15   1页 16 ~ 23
        let satrtIndex = indexPath.item * 8 // 起始位置
        var endIndex = (indexPath.item + 1) * 8 - 1 // 终点位置
        // 判断越界
        if endIndex > groups!.count - 1 {
            endIndex = groups!.count - 1
        }
        
        cell.gropus = Array(groups![satrtIndex...endIndex])
    }
}

extension AmuseMenuView: UICollectionViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 获取滚动的偏移量
        let offsetX = scrollView.contentOffset.x + scrollView.width * 0.5
        pageControl.currentPage = Int(offsetX / scrollView.width) 
    }
    
}
